#include <iostream>
#include <cassert>
#include <string>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "Task.hpp"

const int NUM = 5;
int number = 1;

class channel
{
public:
    channel(int fd, pid_t pid, std::string name = "")
        : _fd(fd), _pid(pid)
    {
        _name += "process ";
        _name += std::to_string(number++);
    }

    int _fd;
    pid_t _pid;
    std::string _name;
};

void Work()
{
    int taskid = 0;
    while (true)
    {
        std::cout << "I am runing!" << std::endl;
        ssize_t n = read(0, &taskid, sizeof(taskid));

        if (n == sizeof(taskid))
        {
            if (init.Check(taskid) == false)
                continue;
            else
                init.Run(taskid);
        }
        else
        {
            break;
        }
    }

    std::cout << "child process quit!" << std::endl;
}

void CreateChannels(std::vector<channel> *c)
{
    for (int i = 0; i < NUM; i++)
    {
        int pipefd[2];
        int n = pipe(pipefd);
        assert(n == 0);
        (void)n;

        pid_t fd = fork();
        assert(fd >= 0);

        if (fd == 0)
        {
            // child
            close(pipefd[1]);
            dup2(pipefd[0], 0);
            Work();
            exit(0);
        }

        close(pipefd[0]);
        c->push_back(channel(pipefd[1], fd));
    }
}

void SendTask(std::vector<channel> &channels, int num)
{
    int pos = 0;
    while (num--)
    {
        int select = init.SelectTask();
        std::cout << "send commend success" << std::endl;
        write(channels[pos]._fd, &select, sizeof(select));

        pos++;
        pos %= channels.size();

        sleep(1);
    }
}

void PrintDebug(std::vector<channel> &channels)
{
    for (int i = 0; i < NUM; i++)
    {
        std::cout << channels[i]._fd << " " << channels[i]._pid << " " << channels[i]._name << std::endl;
    }
}

int main()
{
    srand((unsigned)time(nullptr));

    std::vector<channel> channels;
    // 1.建立管道
    CreateChannels(&channels);
    PrintDebug(channels);

    // 3.发送任务
    SendTask(channels, 100);

    for (auto ch : channels)
    {
        close(ch._fd);
    }

    for (auto ch : channels)
    {
        waitpid(ch._pid, nullptr, 0);
    }

    return 0;
}